package com.lyf.core.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lyf.core.dao.MenuDao;
import com.lyf.core.pojo.Menu;
import com.lyf.core.service.MenuService;
import com.lyf.core.service.UserService;
import com.lyf.core.util.CommonUtils;

@Service
public class MenuServiceImpl implements MenuService {

	Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private MenuDao menuDao;
	
	@Override
	public String add(Menu m) {
		// TODO Auto-generated method stub
		if(m == null || m.getMenu_id() == null){
			return "菜单为空" ;
		}
		
		Menu _m = findById(m.getMenu_id());
		if(_m != null){
			return "菜单ID已存在" ;
		}
		
		//判断实际的父级是否存在,不存在 父级给空
		String p_id = m.getParent_id();
		if(p_id != null && !p_id.trim().equals("")){
			Menu p = findById(p_id);
			if(p == null){
				m.setParent_id(null);
			}
		}
		
		menuDao.insert(m);
		return  null;
	}

	@Override
	public void delete(String menu_id) {
		// TODO Auto-generated method stub
		menuDao.delete(menu_id);
	}

	@Override
	public String update(Menu m) {
		// TODO Auto-generated method stub
		
		//判断父ID 是否存在,如果不存在,父ID 置空
		String p_id = m.getParent_id();
		Menu p_m = findById(p_id);
		if(p_m == null){
			m.setParent_id(null);
		}
		 
		menuDao.update(m);
		return null;
	}

	@Override
	public Menu findById(String menu_id) {
		// TODO Auto-generated method stub
		return menuDao.findById(menu_id);
	}

	@Override
	public List<Menu> findAll(boolean hasPerm,boolean iterChilds , boolean onlyVisible  ) {
		
		
		
		List<Menu> ms =  menuDao.findMenus(1, onlyVisible);
		if(hasPerm){
			List<Menu> _ms =  menuDao.findMenus(2, onlyVisible);
			if(_ms != null){
				ms.addAll(_ms);
			}
		}
		
		if(iterChilds)
			return CommonUtils.childsMenu(ms);
		
		return ms ;
		 
	}

	@Override
	public List<Menu> findByUser(String user_id, boolean hasPerm,  boolean iterChilds) {
		
		if(user_id.equals(UserService.SUPER_ADMIN_ID)){
			List<Menu> ms = findAll(hasPerm, true, iterChilds);
			return ms ;
		}
		
		List<Menu> ms =  menuDao.findMenusByUser(user_id, hasPerm);
		  
		if(iterChilds)
			return CommonUtils.childsMenu(ms);
		
		return ms ;
	}

	@Override
	public void repairMenus() {
		
		//先拿到当前库里的所有菜单项
		List<Menu> dbAll = findAll(true, false, false);
		 
		//在拿到当前应用中扫描的列表
		List<Menu> ctxAll = CommonUtils.getMenus(false, false, null);
		
		//对比 先本地对应数据库
		for(Menu ctx : ctxAll) {
			boolean has = false;
			for(Menu db : dbAll) {
				if(db.getMenu_id().equals(ctx.getMenu_id())){
					has = true ;
					break;
				}
			}
			
			//不存在的话 追加进入数据库
			if(!has){
				logger.info("ctx sync db menu,menu: " + ctx);
				add(ctx);
			}
			
		}
		
		//数据库有,本地没有了先进行隐藏
		
		
	}

}
